package com.baosight.innerinterface.service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiBlockMeta;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.spring.SpringApplicationContext;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.dao.Dao;
import com.baosight.iplat4j.ed.util.CodesetBiz;
import com.baosight.iplat4j.ed.util.SequenceGenerator;
import com.baosight.iplat4j.ep.DaoEPBase;
import com.baosight.iplat4j.security.bridge.SecurityBridgeFactory;

import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class SOUtils {
	private static final String COMPANY_CODE = "account";
	private static final String COMPANY_NAME = "companyName";
	private static int itemSeqNum = 0;

	public static String getItemValue(String Code, String Key) {
		String itemValue = " ";
		CodesetBiz codeBiz = (CodesetBiz) SpringApplicationContext.getBean("codesetBiz");
		List list = codeBiz.getCodeSet(Code, "item_code = '" + Key + "'");
		if (list.size() > 0) {
			String CodeSet = list.get(0).toString();
			itemValue = CodeSet.substring(CodeSet.indexOf(", label=") + 8, CodeSet.length() - 1);
		}
		return itemValue;
	}

	// 根据帐套生成序列号：传入参数账套,平台页面维护序列号名称
	public static String getSeqValue(String company_code, String seqTypeName) {
		String str = company_code.split("\\.")[1].toString(); // 根据获取帐套(bssim.00)
																// 截取小数点后面数据(得到00)
		String getcompany = StringUtils.leftPad(str, 8, "*") + "-";// 不足8位补齐数据长度
																	// ,以短横杆结束(******00-)
		String[] args = { getcompany };// 放入字符串数组中,方便参数传递
		String idStr = SequenceGenerator.getNextSequence(seqTypeName, args).split("-")[1].toString();// 生成带帐套序列号后，截取掉帐套及段横杆，返回获得的序列号
		return idStr;
	}

	// 根据帐套生成序列号：传入参数账套,自己所需参数,平台页面维护序列号名称
	public static String getSeqValue(String company_code, String seqTypeName, String[] args) {
		String str = company_code.split("\\.")[1].toString(); // 根据获取帐套(bssim.00)
																// 截取小数点后面数据(得到00)
		String getcompany = StringUtils.leftPad(str, 8, "*") + "-";// 不足8位补齐数据长度
																	// ,以短横杆结束(******00-)

		String[] companyArgs = { getcompany };// 放入字符串数组中,方便参数传递
		String[] allArgs = concatAll(companyArgs, args);
		String idStr = SequenceGenerator.getNextSequence(seqTypeName, allArgs).split("-")[1].toString();// 生成带帐套序列号后，截取掉帐套及段横杆，返回获得的序列号
		return idStr;
	}

	/**
	 * 合并多个数组为一个数组
	 * 
	 * @param first
	 * @param rest
	 * @return
	 */
	public static <T> T[] concatAll(T[] first, T[]... rest) {
		int totalLength = first.length;
		for (T[] array : rest) {
			totalLength += array.length;
		}
		T[] result = Arrays.copyOf(first, totalLength);
		int offset = first.length;
		for (T[] array : rest) {
			System.arraycopy(array, 0, result, offset, array.length);
			offset += array.length;
		}
		return result;
	}

	public static String getItemValue(String tableName, String key, String valueColumn, String labelColumn) {
		String itemValue = " ";
		HashMap paraMap = new HashMap();
		paraMap.put("tableName", "SOADMIN." + tableName);
		paraMap.put("valueColumn", valueColumn);
		paraMap.put("labelColumn", labelColumn);
		paraMap.put("key", key);
		List list = null;
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		list = dao.query("tsoutils.query", paraMap);
		if (list.size() > 0) {
			itemValue = list.get(0).toString();
		}
		return itemValue;
	}

	public static EiBlock generateBlock(String id, DaoEPBase bean, String sql, HashMap paraMap) {
		EiBlock block = new EiBlock(id);
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		block.setBlockMeta(bean.eiMetadata);
		int offset = 0;
		int limit = 1000;
		int size = 1000;
		List returnList = null;
		int totalSize = 0;
		while (size == limit) {
			try {
				returnList = dao.query(sql, paraMap, offset, limit);
				if (returnList != null) {
					size = returnList.size();
					block.addRows(returnList);
				} else {
					size = 0;
				}
				offset += limit;
				totalSize += size;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return block;
	}

	public static EiInfo getQualityPara(String productCode) {
		EiInfo outInfo = new EiInfo();
		HashMap paraMap = new HashMap();
		paraMap.put("productCode", productCode);
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		List list = null;
		list = dao.query("SOSI98.queryelement", paraMap);
		EiBlock inBlock = new EiBlock("bean");
		for (int i = 0; i < list.size(); i++) {
			Map map = (Map) list.get(i);
			String beanCode = map.get("elementCode").toString();
			String beanName = map.get("elementName").toString();
			inBlock.setCell(i, "beanCode", beanCode);
			inBlock.setCell(i, "beanValue", 0);
			inBlock.setCell(i, "beanName", beanName);
		}
		outInfo.set("qualityPara", createQualityParaXml(inBlock));
		outInfo.set("qualityDesc", createQualityDesc(inBlock));
		return outInfo;
	}

	/**
	 * 
	 * @author DongLe Dom4j EiInfo生成XML与解析XML为EiInfo
	 */

	public static String createQualityParaXml(EiBlock inBlock) {
		Document document = DocumentHelper.createDocument();
		Element beans = document.addElement("beans");
		for (int num = 0; num < inBlock.getRowCount(); num++) {
			Element bean = beans.addElement("bean");
			Element code = bean.addElement("beanCode");
			code.setText(inBlock.getCellStr(num, "beanCode"));

			Element codeName = bean.addElement("beanName");
			codeName.setText(inBlock.getCellStr(num, "beanName"));

			Element value = bean.addElement("beanValue");
			value.setText(inBlock.getCellStr(num, "beanValue"));
		}
		String documentStr = document.asXML();
		return documentStr;
	}

	public static String createQualityDesc(EiBlock inBlock) {
		String descStr = "";
		for (int num = 0; num < inBlock.getRowCount(); num++) {
			descStr += inBlock.getCellStr(num, "beanName") + ":" + inBlock.getCellStr(num, "beanValue") + "; ";
		}
		if (descStr.equals("")) {
			descStr = " ";
		}
		return descStr;
	}

	public static EiBlock parserQualityParaXml(String xmlStr, String blockName) throws Exception {

		EiBlock outBlock = new EiBlock(blockName);
		EiBlockMeta metadata = new EiBlockMeta();

		EiColumn eiColumn = new EiColumn("beanCode");
		eiColumn.setDescName("代码");
		metadata.addMeta(eiColumn);

		eiColumn = new EiColumn("beanName");
		eiColumn.setDescName("描述");
		metadata.addMeta(eiColumn);

		eiColumn = new EiColumn("beanValue");
		eiColumn.setDescName("值");
		metadata.addMeta(eiColumn);

		outBlock.setBlockMeta(metadata);

		if (xmlStr != null && !xmlStr.isEmpty()) {

			Document document = DocumentHelper.parseText(xmlStr);
			Element beans = document.getRootElement();
			for (Iterator i = beans.elementIterator(); i.hasNext();) {
				Element bean = (Element) i.next();
				Map row = new HashMap();
				for (Iterator j = bean.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();
					row.put(node.getName(), node.getText());
				}
				outBlock.addRow(row);
			}
		}
		return outBlock;
	}

	/**
	 * 向目标EiBlockMeta中添加meta
	 * 
	 * @Title: initMetaData
	 * @return
	 */
	public static EiBlockMeta initMetaData(EiBlockMeta sourceMeta, Map<String, String> addParams) {
		EiColumn eiColumn;
		for (Map.Entry<String, String> entry : addParams.entrySet()) {
			eiColumn = new EiColumn(entry.getKey());
			eiColumn.setDescName(entry.getValue());
			sourceMeta.addMeta(eiColumn);
		}
		return sourceMeta;
	}

	/**
	 * 查询平台表
	 * 
	 * @param key
	 * @return
	 */
	public static String getItemValueForIplat(String tableName, String labelColumn, String valueColumn, String key) {
		String itemValue = "";

		HashMap paraMap = new HashMap();
		paraMap.put("tableName", "IPLAT." + tableName);
		paraMap.put("labelColumn", labelColumn);
		paraMap.put("valueColumn", valueColumn);
		paraMap.put("key", key);
		List list = null;
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		list = dao.query("InDesignInterface.query", paraMap);
		if (list.size() > 0) {
			itemValue = list.get(0).toString();
		}
		return itemValue;
	}

	public static String getCompanyCode() {
		String companyCode = (String) UserSession.getInSessionProperty(COMPANY_CODE);

		String companyName = (String) UserSession.getInSessionProperty(COMPANY_NAME);

		if (companyCode != null && companyName == null) {
			companyName = SecurityBridgeFactory.getBridge().getAuthzNodeDisplayName(companyCode);
			UserSession.setOutSessionProperty(COMPANY_NAME, companyName);
		}

		return companyCode;
	}

	/**
	 * 子项序号
	 * 
	 * @param seqNum
	 *            起始顺序号
	 * @param sqlName
	 *            查询语句
	 * @param param
	 *            查询参数
	 * @return
	 * @throws Exception
	 */
	public static Integer getSeq(int seqNum, String sqlName, Map<Object, Object> param) throws Exception {
		Dao dao = (Dao) SpringApplicationContext.getBean("dao");
		itemSeqNum = Integer.valueOf(StringUtils.defaultIfEmpty(String.valueOf(seqNum), String.valueOf(itemSeqNum)));

		String seqNo = StringUtils.EMPTY;

		boolean flag = false;

		for (; itemSeqNum <= 99999999; itemSeqNum++) {
			seqNo = "00000000".substring(String.valueOf(itemSeqNum).length()) + String.valueOf(itemSeqNum);

			param.put("seqNo", seqNo);
			List list;
			try {
				list = dao.query(sqlName, param);
			} catch (Exception e) {
				throw new Exception(e);
			}

			if (list.size() > 0) {
				continue;
			} else {
				flag = true;
				break;
			}
		}

		if (flag) {
			return Integer.valueOf(seqNo);
		} else {
			return null;
		}
	}

}